import React, {useState, useEffect, useRef} from 'react';
import {Text, View, StyleSheet, TouchableOpacity, ScrollView, Image, DeviceEventEmitter} from 'react-native';
import {useNavigation, useRoute} from '@react-navigation/native';
import screen from '../../utils/screen';
import Container from '../../components/Container';
import Images from '../../images/images';
import TouchableView from '../../components/touchableView';
import LinkButton from '../../components/linkButton';
import {useToast} from '../../components/toast/useToast';
import BleUtil from '../../utils/bleUtil';
import store from 'react-native-simple-store'
import _ from 'lodash'
import {useLoading} from '../../components/loading/useLoading';
import {formatTimestamp} from '../../utils/dateUtil';
import {EventName, getByteLength} from '../../utils/common';
import TemplateItem from '../../components/templateItem';
import {useAppStore} from '../../store/useAppStore';
import { setTemplateCmd} from '../../utils/bleCmd';



const Template = ()=>{
    const navigation = useNavigation()
    const route = useRoute()
    const toast = useToast()
    const loading = useLoading()
    const {data} = route.params
    const [list,setList] = useState([])
    const [time,setTime] = useState(null)
    const storeKey = data ? `device_${data.id}` : 'localData'
    const storeData = useRef(null)
    const timerRef = useRef(null)
    const {appState:{currentDevice,pressure},updateAppState }= useAppStore()

    useEffect(()=>{
        getTemplate()

        const notifyListener = BleUtil.addNotifyListener((info,cmd)=>{
            console.log('message notify:',cmd,info);
        })

        return ()=>{
            notifyListener.remove()
            timerRef.current && clearInterval(timerRef.current)
        }

    },[])



    useEffect(()=>{

        navigation.setOptions({
            headerRight:()=>(
                <TouchableOpacity
                    style={{paddingRight:screen.PIXEL_30}}
                    onPress={()=>{
                        if(list.length >= 5){
                            toast.show('模板数量已满，请删除后再添加')
                            return
                        }
                        navigation.navigate('TemplateEdit',{
                            callback:(newData)=>{
                                saveNewMessage(newData)
                            }
                        })
                    }}
                >
                    <Text>添加模板</Text>
                </TouchableOpacity>
            ),
        })

        updateLocalData(list)

    },[list])

    const updateLocalData = (list,syncTime)=>{
        if(!storeData.current) return
        let message = storeData.current.message ?? {  }
        if(list){
            message.list = list
        }
        if(syncTime){
            message.syncTime = syncTime
        }
        let newData = {
            ...storeData.current,
            message
        }
        storeData.current = newData
        store.save(storeKey,newData).then(()=>{
            DeviceEventEmitter.emit(EventName.countUpdate)
        })
    }

    const getTemplate = ()=>{
        store.get(storeKey).then(res=>{
            if(res){
                storeData.current = res
                if(!res.message) return
                const {list,syncTime} = res.message
                setList(list)
                setTime(syncTime)

            }else{
                storeData.current = {}
            }
            // console.log(storeKey,res);
        })


    }

    const sendCmd = (cmd)=>{

        BleUtil.write(data.id,cmd).then(()=>{
            console.log(cmd);
        }).catch(error=>{
            console.log('write error:',error);
        })

    }

    const sendCmdList = (cmdList,isSync)=>{
        BleUtil.clearResults()
        let promiseList = []
        cmdList.forEach((cmd,index)=>{
            let promise = new Promise((fulfill,reject)=>{
                setTimeout(()=>{
                    BleUtil.writeWithoutResponse(data.id,cmd).then(()=>{
                        console.log(index +' cmd send',);
                        fulfill(cmd)
                    }).catch(error=>{
                        reject(error)
                    })
                },500 * index)
            })
            promiseList.push(promise)
        })
        Promise.all(promiseList).then(values=>{

            timerRef.current && clearInterval(timerRef.current)
            timerRef.current = setInterval(()=>{
                const results = BleUtil.checkResults()
                if(!results.length) return
                console.log(results);
                const lastResult = results[results.length - 1]
                const findIndex = values.findIndex(it=>{
                    return it.includes(lastResult.cmd)
                })
                if(findIndex > -1){
                    console.log(values[findIndex] + ',' ,lastResult.result);

                    if(isSync ){
                        if(lastResult.result.includes('result: 0')){
                            //同步成功 判断是否是最后一条指令
                            if(findIndex == values.length - 1){
                                clearInterval(timerRef.current)
                                loading.hide()
                                toast.showSuccess('同步成功')
                                const syncTime = formatTimestamp(new Date(),'yyyy/MM/dd hh:mm:ss')
                                setTime(syncTime)
                                updateLocalData(null,syncTime)
                            }
                        }else{
                            //有一个同步失败 则
                            clearInterval(timerRef.current)
                            loading.hide()
                            toast.show('同步失败，请重试')
                        }
                    }else{
                        if(findIndex == values.length - 1){
                            clearInterval(timerRef.current)
                        }
                    }
                }
            },1000)

        }).catch(error=>{
            console.log(error);
            if(isSync){
                loading.hide()
                toast.show('同步失败，请重试')
            }
        })


    }

    const onSyncClick = ()=>{
        if(!list.length) return

        BleUtil.isPeripheralConnected(data.id).then(isConnected=>{
            console.log('是否连接',isConnected);
            if(isConnected){
                syncToDevice()
            }else{
                toast.show('设备已断开连接,请重新连接')
                updateAppState({
                    currentDevice:null,
                    battery:0
                })

            }
        })
    }
    const parseMessage = (message)=>{
        if(message.includes('[位置]')){
            message = message.replaceAll('[位置]',' <gps>')
        }
        if(message.includes('[海拔]')){
            message = message.replaceAll('[海拔]',' <alt>')
        }
        if(message.includes('[气压]')){
            message = message.replaceAll('[气压]',' <atmo>' )
        }
        if(message.includes('[设备]')){
            message = message.replaceAll('[设备]',' ' + currentDevice.name )
        }
        return message
    }

    const syncToDevice = ()=>{

        loading.show('同步中')
        const sosMsg = `我遇到了危险 <gps>，急需救援`
        let cmdList = [setTemplateCmd(sosMsg,0)]
        for (let i = 0; i < 5; i++) {
            if(i < list.length){
                let item = list[i]
                let message = _.clone(item.message)
                message = parseMessage(message)
                const cmd = setTemplateCmd(message,i)
                cmdList.push(cmd)
            }else{
                //删除
                const cmd = `delTemplate ${i + 1} seq[31]\r\n`
                cmdList.push(cmd)
            }
        }
        cmdList.push('setTemplate  255\r\n')
        sendCmdList(cmdList,true)

    }




    const saveNewMessage = (newData)=>{
        console.log(newData);
        if(newData.delete){
            setList(prevState => {
                let newList = _.clone(prevState)
                let findIndex = newList.findIndex(it=>{
                    return it.index === newData.index
                })
                newList.splice(findIndex,1)
                // if(newList.length){
                //     const cmd = 'delTemplate '+ newData.index +'\r\n'
                //     sendCmd(cmd)
                // }else{
                //     const cmd = 'delTemplate 0'+ '\r\n'
                //     sendCmd(cmd)
                // }
                return newList
            })
            return
        }

        if(newData.index){
            //替换
            setList(prevState => {
                let newList = _.clone(prevState)
                let findIndex = newList.findIndex(it=>{
                    return it.index === newData.index
                })
                newList.splice(findIndex,1,newData)
                return newList
            })

        }else{
            //新增
            setList(prevState => {
                let obj = {...newData,index:prevState.length + 1}
                let newList = _.clone(prevState)
                newList.unshift(obj)
                return newList
            })
        }
    }



    return (
        <Container >
            {
                time  ? (
                    <View style={styles.timeBg}>
                        <Text style={{color:'#0D80FC',textAlign:'center'}}>上次同步时间:{time}</Text>
                    </View>
                ) : null
            }
            <ScrollView
                contentContainerStyle={{padding:screen.PIXEL_30}}
            >

                {list.map((item,index)=>{
                    return (
                        <TemplateItem
                            key={index.toString()}
                            message={item.message}
                            onPress={()=>{
                                navigation.navigate('TemplateEdit',{data:item,
                                    callback:(newData)=>{
                                        saveNewMessage(newData)
                                    }
                                })
                            }}
                        />

                    )
                })}

            </ScrollView>

            <LinkButton
                title={'同步模版到设备'}
                style={{alignSelf:'center',marginBottom:screen.PIXEL_120,marginTop:screen.PIXEL_30}}
                onPress={onSyncClick}
            />

        </Container>
    )
}
export default Template

const styles = StyleSheet.create({
    container: {
        flex: 1, justifyContent: 'center', alignItems: 'center'
    },

    timeBg:{
        height:screen.PIXEL_60,width:'100%',backgroundColor:'rgb(212,229,252)',flexDirection: 'row',
        alignItems: "center",justifyContent:'center'
    },
    rowCenter: {
        flexDirection: 'row', alignItems: "center"
    },
    moduleView: {
        backgroundColor: '#fff', borderRadius: screen.PIXEL_20, height: screen.PIXEL_100,
        paddingHorizontal: screen.PIXEL_30, marginBottom: screen.PIXEL_40, justifyContent: 'center'
    },

    tagBg:{
        backgroundColor: '#0D80FC',height:screen.PIXEL_40,justifyContent:'center',
        borderRadius: screen.PIXEL_20,paddingHorizontal: screen.PIXEL_20,marginRight:screen.PIXEL_20
    }
})
